#include "XmlSerializer.h"
#include <xercesc/framework/MemBufFormatTarget.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include "NullPointerException.h"
#include "XmlStringTranscoder.h"

namespace etu {
namespace common {

DOMDocument* XmlSerializer::createDocument(const char* rootNodeName) {
    this->domImpl = DOMImplementationRegistry::getDOMImplementation(X("Core"));
    return this->domImpl->createDocument(0, X(rootNodeName), 0);
}

std::string XmlSerializer::documentToString(DOMDocument* doc) {
    std::ostringstream ret;
    DOMWriter* domWriter = this->domImpl->createDOMWriter();
    XMLFormatTarget *myFormatTarget = new MemBufFormatTarget();

    domWriter->writeNode(myFormatTarget, *doc);
    char* xmlData =
        (char*) ((MemBufFormatTarget *) myFormatTarget)->getRawBuffer();
    ret << xmlData;

    return ret.str();
}

DOMDocument* XmlSerializer::buildDocument(const std::string& str) {
    static const char* bufferId = "xml_buffer";

    MemBufInputSource src((const XMLByte *) str.c_str(), str.length(), bufferId);
    XercesDOMParser* parser = new XercesDOMParser();
    parser->parse(src);

    DOMDocument* ret = dynamic_cast<DOMDocument *>(parser->getDocument());

    // TODO throw XmlParseException if doc == NULL or any other exception has been got

    // commented to prevent DOMDocument structure
    //delete parser;

    return ret;
}

}
}
